﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

public partial class TaskNewAccept : PMSBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.TableName = "PMS_TaskLX";
        this.Key = "TaskID"; 
        if ((!string.IsNullOrEmpty(Request["isgroup"]) && Convert.ToBoolean(Request["isgroup"])) || hfIsGroup.Value == "true")
        {
            hfIsGroup.Value = "true";
        }
        if (!IsPostBack)
        {
            InitData();
            btnSave.Visible = false;
            DataSet tempds = PMSAccess.GetDataSet(this.Connection, "select distinct HouseNo from PMS_CUSTOMER where HouseNo is not null and HouseNo<>'' order by HouseNo");

            cbHouseNo.DataSource = tempds.Tables[0];
            cbHouseNo.DataTextField = "HouseNo";
            cbHouseNo.DataValueField = "HouseNo";
            cbHouseNo.DataBind();
            cbHouseNo.Items.Insert(0, new ListItem("请选择", ""));

            tbPhone.Attributes.Add("onkeypress", "Openfree.prototype.EnterSubmit('" + tbPhone.ClientID + "',event);");
        }
        else
        {
            string phone = tbPhone.Text.Trim();
            if (phone.Length > 0 && string.IsNullOrEmpty(tbGuest.Text.Trim()))
            {
                phone = phone.Replace("'", string.Empty);
                tbPhone.Text = phone;
            }
            else
            {
                return;
            }
            string cmdText = "select top 1 * from PMS_Customer where Telephone='{0}'";
            cmdText = string.Format(cmdText, phone);
            DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText);
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                tbGuest.Text = dr["Units"].ToString();
                cbHouseNo.SelectedValue = dr["HouseNo"].ToString();
                tbRoomNo.Text = dr["RoomNo"].ToString();
            }
        }
    }
    private void InitData()
    {
        this.lbCreateDate.Text = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm");
        this.lbUserID.Text = SessionManager.Username;
        this.lbOrgID.Text = SessionManager.OrgName;
        string cmdText = "select * from PMS_TaskLX where 1=2";

        DataSet ds = BaseAccess.GetDataSet(base.Connection, cmdText, this.TableName);
        SessionManager.DataSet = ds;
        TaskPersonItem.ShowWorkTime = false; 
        TaskPersonItem.InitData("TaskID", System.Guid.NewGuid().ToString());

    }
    private void ClearValue()
    {
        hfTaskID.Value = "";
        tbGuest.Text = "";
        cbHouseNo.SelectedValue="";
        tbRoomNo.Text = "";
        tbPhone.Text = "";
        tbTroubleDescription.Text = "";
        cbIsReqGood.Checked = false;
        cbIsAutoUpdate.Checked = false;
        this.lbCreateDate.Text = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm");
        this.lbUserID.Text = SessionManager.Username;
        this.lbOrgID.Text = SessionManager.OrgName;
    }
    private void btnPhone_Changed(object sender, EventArgs e)
    {
        this.tbGuest.Text = "test";
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {

        //判断是否选择领单人
        string result = TaskPersonItem.PreProcessSave();
        
        DataRow row = SessionManager.DataSet.Tables[this.TableName].NewRow();
        string taskId = Guid.NewGuid().ToString();
        row["TaskID"] = taskId;
        hfTaskID.Value = taskId;
        //row["TaskCode"] =
        row["Guest"] = tbGuest.Text.Trim();
        row["HouseNo"] = cbHouseNo.SelectedValue;
        row["RoomNo"] = tbRoomNo.Text.Trim();
        row["Phone"] = tbPhone.Text.Trim();
        row["TroubleDescription"] = tbTroubleDescription.Text.Trim();
        row["UserID"] = SessionManager.UserID;
        row["OrgID"] = SessionManager.OrgID;
        row["CreateDate"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
        row["GoodsState"] = PMSGoodsState.NotOut;
        row["TaskState"] = PMSTaskState.Running;
        row["SourceState"] = PMSSourceState.From123;
        row["IsRequestGood"] = cbIsReqGood.Checked;
        SessionManager.DataSet.Tables[this.TableName].Rows.Add(row);

        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select * from PMS_TaskItem where TaskID='" + taskId + "' ", "PMS_TaskItem");
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select * from IC_Requisition where TaskID='" + taskId + "' ", "IC_Requisition");
        if (SessionManager.DataSet.Tables.Contains(TaskPersonItem.m_TableName))
        {
            DataTable dt = SessionManager.DataSet.Tables[TaskPersonItem.m_TableName];
            if (dt != null && dt.Rows.Count > 0)
            {
                //row["TaskState"] = PMSTaskState.Dispatch;
                List<string> list = new List<string>();
                DataRow itemrow = null;
                string taskItemId = null;
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    if (!list.Contains(dr["GroupCode"].ToString()))
                    {
                        list.Add(dr["GroupCode"].ToString());
                        taskItemId = System.Guid.NewGuid().ToString();
                        itemrow = SessionManager.DataSet.Tables["PMS_TaskItem"].NewRow();
                        itemrow["TaskItemID"] = taskItemId;
                        itemrow["TaskID"] = taskId;
                        itemrow["SNYear"] = DateTime.Now.ToString("yyyy");
                        itemrow["SNGroup"] = dr["GroupCode"];
                        itemrow["SNTask"] = PMSCodeCategory.PMS_RCLX;
                        itemrow["SNProject"] = "01";
                        itemrow["SNDispatch"] = DocumentHelper.Instance.GetDispatchCode(itemrow["SNYear"].ToString(), dr["GroupCode"].ToString(), PMSCodeCategory.PMS_RCLX, "01");
                        itemrow["TaskState"] = PMSTaskState.Running;
                        itemrow["TaskCode"] = itemrow["SNYear"].ToString() + itemrow["SNGroup"].ToString() + itemrow["SNTask"].ToString() + itemrow["SNProject"].ToString() + itemrow["SNDispatch"].ToString();
                        PMSAccess.AppendValue(ref itemrow, EnumOperator.ADD);
                        SessionManager.DataSet.Tables["PMS_TaskItem"].Rows.Add(itemrow);
                        if (cbIsReqGood.Checked)
                        {
                            string guid = System.Guid.NewGuid().ToString();
                            DataRow req_dr = SessionManager.DataSet.Tables["IC_Requisition"].NewRow();
                            req_dr["RequisitionID"] = guid;
                            req_dr["TaskID"] = taskItemId;
                            req_dr["Status"] = PMSGoodsState.NotOut;
                            req_dr["GetUserID"] = dr["UserID"];
                            req_dr["RequisitionType"] = PMSCodeCategory.PMS_RKLX_LingLiao;
                            req_dr["RequisitionCode"] = PMSAccess.GetCode(EnumCodeKind.LingLiao);
                            req_dr["RequisitionUser"] = SessionManager.Username;
                            req_dr["RequisitionDate"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                            PMSAccess.AppendValue(ref req_dr, EnumOperator.ADD);
                            SessionManager.DataSet.Tables["IC_Requisition"].Rows.Add(req_dr);
                        } 
                    }
                    dr["TaskID"] = itemrow["TaskItemID"];
                    //设置领单人类型
                    dr["UserType"] = PMSCodeCategory.UserReceiver;
                    dr["OrgID"] = SessionManager.OrgID;
                    dr["CreateTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                    dr["CreateUser"] = SessionManager.LoginName;
                }
            } 
        }
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, "select * from PMS_CUSTOMER where Telephone='" + tbPhone.Text.Trim()+ "' and HouseNo='" + cbHouseNo.SelectedValue + "' and RoomNo='" + tbRoomNo.Text.Trim() + "'", "PMS_CUSTOMER");
        if (cbIsAutoUpdate.Checked)
        {
            if (SessionManager.DataSet.Tables["PMS_CUSTOMER"].Rows.Count == 0)
            {
                DataRow _row = SessionManager.DataSet.Tables["PMS_CUSTOMER"].NewRow();
                _row["CustomerID"] = System.Guid.NewGuid().ToString();
                _row["HouseNo"] = cbHouseNo.SelectedValue;
                _row["RoomNo"] = tbRoomNo.Text.Trim();
                _row["Telephone"] = tbPhone.Text;
                _row["RoomName"] = tbGuest.Text;
                _row["Units"] = tbGuest.Text;
                SessionManager.DataSet.Tables["PMS_CUSTOMER"].Rows.Add(_row);
            }
            else
            {
                DataRow _row = SessionManager.DataSet.Tables["PMS_CUSTOMER"].Rows[0];
                _row["HouseNo"] = cbHouseNo.SelectedValue;
                _row["RoomNo"] = tbRoomNo.Text.Trim();
                _row["Telephone"] = tbPhone.Text;
                _row["RoomName"] = tbGuest.Text;
                _row["Units"] = tbGuest.Text;
            }
        }
        PMSAccess.UpdateDataSet(this.Connection, new string[] { this.TableName, "PMS_TaskUser", "PMS_TaskItem", "IC_Requisition", "PMS_CUSTOMER" }, SessionManager.DataSet);
        
        //导出派工单
        //string filePath = Server.MapPath(SessionManager.TempVirtualFolder + System.Guid.NewGuid().ToString() + ".doc");
        //string outinfo = DocumentHelper.ExportAllDispatchDocument(PMSConst.PMSDispatchDocTemplatePath, filePath, taskId);
        //if (string.IsNullOrEmpty(outinfo))
        //{
        //    //base.DownLoadFile(filePath, "派工单.doc");
        //    ifdown.Attributes["src"] = filePath;
        //}
        //ClearValue();
        //InitData();
        //tipMessage1.ShowMessage("受理成功", 5000);
        Response.Redirect("TaskDispatch.aspx?isgroup="+hfIsGroup.Value);
    }
    protected void btnSelect_Click(object sender, EventArgs e)
    {
        if (TaskPersonItem.OnSelect != null)
        {
            btnSave.Visible = true;
            TaskPersonItem.OnSelect(sender, e);
            if(hfIsGroup.Value=="true")
                TaskPersonItem.SetGroupReadOnly(SessionManager.UserGroupCode);
        }
    }
    protected void btnListDocument_Click(object sender, EventArgs e)
    {
        //任务taskID
        string taskID = hfTaskID.Value;
        if (string.IsNullOrEmpty(taskID))
        {
            tipMessage1.ShowMessage("请先填写报修信息，并受理任务！", 5000);
            return;
        }
        string filePath = Server.MapPath(SessionManager.TempVirtualFolder + System.Guid.NewGuid().ToString() + ".doc");
        string outinfo = DocumentHelper.ExportAllDispatchDocument(PMSConst.PMSDispatchDocTemplatePath, filePath, taskID);
        if (string.IsNullOrEmpty(outinfo))
        {
            ifdown.Attributes["src"] = "../SiteAdmin/DownLoadHandler.ashx?url=" +
                filePath + "&name=" + HttpUtility.UrlEncode("派工单.") + DateTime.Now.ToString("MMdd.HHmmss") + ".doc";
            //base.DownLoadFile(filePath, "派工单.doc");
        }
        else
        {
            //tipMessage1.ShowMessage(outinfo, 5000);
        }
        //btnListDocument.Visible = false;
    }
}
